package com.udata.client.user;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.udata.client.service.UserService;
import com.udata.client.service.UserServiceAsync;
import com.udata.client.stoke.StokeWidget;
import com.udata.shared.model.UserB;

public class RegisterWidget extends Composite {

	private UserServiceAsync userService = GWT.create(UserService.class);

	private StokeWidget stockWidget = new StokeWidget();

	interface MyUiBinder extends UiBinder<HTMLPanel, RegisterWidget> {
	}

	public RegisterWidget() {

		initWidget(uiBinder.createAndBindUi(this).asWidget());
	}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	@UiField
	TextBox id;
	@UiField
	TextBox name;
	@UiField
	TextBox password;
	@UiField
	TextBox email;
	@UiField
	Button register;

	@UiHandler("register")
	void handleClick(ClickEvent e) {
		UserB userB = new UserB();
		userB.setId(id.getText());
		userB.setName(name.getText());
		userB.setPassword(password.getText());
		userB.setEmail(email.getText());
		userService.save(userB, new AsyncCallback<UserB>() {

			@Override
			public void onFailure(Throwable caught) {
				GWT.log(caught.getLocalizedMessage());
				Window.alert("Can not register:User already exist");
			}

			@Override
			public void onSuccess(UserB result) {
				GWT.log("success");
				Cookies.setCookie("PSFE_user",
						result.getId() + ";" + result.getName());
				GWT.log(Cookies.getCookieNames().toString());
				RootPanel.get().clear();
				RootPanel.get().add(stockWidget);
			}
		});
	}

}
